package com.indexingsystem.boss.utils;

import java.lang.reflect.Type;
import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class JsonUtils {

	private static final Gson		gson	= new GsonBuilder().registerTypeAdapter( Date.class, new GsonDateTypeAdapter() ).serializeNulls()
													.create();
	private static SerializeConfig	mapping	= new SerializeConfig();
	private static String			dateFormat;
	static {
		dateFormat = "yyyy-MM-dd HH:mm:ss";
	}

	public static String toJson(Object obj) {
		return gson.toJson( obj );
	}

	public static <T> T fromJson(String json, Class<T> classOfT) {
		return gson.fromJson( json, classOfT );
	}

	/**
	 * <pre>
	 * Type typeOfT = new TypeToken&ltCollection&ltFoo&gt&gt(){}.getType();
	 * Collection&ltFoo&gt foos = JsonUtils.fromJson(json,typeOfT)
	 * </pre>
	 * 
	 * @param json
	 *            json格式的字符串.
	 * @param typeOfT
	 * @return
	 */
	public static <T> T fromJson(String json, Type typeOfT) {
		return gson.fromJson( json, typeOfT );
	}

	/**
	 * 自定义时间格式
	 * 
	 * @param jsonText
	 * @return
	 */
	public static String toJSON(String dateFormat, String jsonText) {
		mapping.put( Date.class, new SimpleDateFormatSerializer( dateFormat ) );
		return JSON.toJSONString( jsonText, mapping );
	}
}
